<?php
namespace Action;
use HY\Action;
!defined('HY_PATH') && exit('HY_PATH not defined.');
class Tunnel extends HYBBS {

    //类中使用的路径

	public function __construct() {
		parent::__construct();
		//{hook a_post_init}
		if(!IS_LOGIN){
			if(IS_AJAX && IS_POST){
				die($this->json(array('error'=>false,'info'=>'请登录后再操作')));
			}
			else{
				header("location: ". HYBBS_URLA('user','login'));
				die;
			}

		}
	}

	public function TCPView(){
		//打开接收任务界面
		$task = S('fhl_ctask')->query('select * from hy_fhl_stask')->fetchALL();
        $this->v("title","画方");
        $this->v("title2","全流量加速系统");
		$this->view = 'CQQ';
		$this->display('TCPTunnel');

	}
    public function UDPView(){
        //打开接收任务界面
        $task = S('fhl_ctask')->query('select * from hy_fhl_stask')->fetchALL();
        $this->v("title","画方");
        $this->v("title2","全流量加速系统");
        $this->view = 'CQQ';
        $this->display('UDPTunnel');

    }
	public function Tview(){
		//打开发送任务界面
		$task = S('fhl_ctask')->query('')->fetchALL();
		$this->v('task',$task);
		$this->view = 'FHL';
		$this->display('Ttask');

	}
	public function editTask(){
		$taskid = intval(X("post.taskid"));
		$type = X("post.type");
		$info = X("post.info");
		$m = X("post.mode");
		$port = intval(X("post.port"));
        $lport = $port+1000;
        //$this->json(array('error'=>true,'info'=>'修改成功'));
		if($type == 't'){
			//修改发送任务
			$p = intval(X("post.p"));
			$ip = X("post.ip");
			//如果是主任务 要同时修改接收任务模式
            //如果不是主任务 则不能修改漠视你
            if($taskid == 0){
                S('fhl_ctask')->update([
                    'info'=>$info,
                    'm'=>$m,
                    'ip'=>$ip,
                    'port'=>$port,
                    'lport'=>$lport,
                    'p'=>$p
                ],[
                    'taskid'=>$taskid
                ]);
                S('fhl_stask')->update([
                    'm'=>$m,
                ],[
                    'taskid[>]'=>0
                ]);
            }else{
                S('fhl_ctask')->update([
                    'info'=>$info,
                    'ip'=>$ip,
                    'port'=>$port,
                    'lport'=>$lport,
                    'p'=>$p
                ],[
                    'taskid'=>$taskid
                ]);
            }
			$this->json(array('error'=>true,'info'=>'修改成功'));
		}elseif($type == 'r'){
			//修改接收任务
            if($taskid == 0){
                S('fhl_stask')->update([
                    'info'=>$info,
                    'm'=>$m,
                    'port'=>$port,
                ],[
                    'taskid'=>$taskid
                ]);
                S('fhl_ctask')->update([
                    'm'=>$m,
                ],[
                    'taskid[>]'=>0
                ]);
            }else{
                S('fhl_stask')->update([
                    'info'=>$info,
                    'm'=>$m,
                    'port'=>$port,
                ],[
                    'taskid'=>$taskid
                ]);
            }

			$this->json(array('error'=>true,'info'=>'修改成功'));

		}


}
	public function restartTask(){
		$type = X('get.type');
		$taskid = intval(X('get.taskid'));
		if($type == 't'){
		    //发送任务
			$task = S('fhl_ctask')->query('select * from hy_fhl_ctask where taskid = '.$taskid)->fetchALL()[0];
			$this->existFHLexe("FengHoLn_ct".$taskid.'.exe');
			$this->existFHLdir(C('FHLdirroot').$task['SD']);
            exec('taskkill /f /im FengHoln_ct'.$taskid.'.exe',$out);
			$cmd ='start /b '.PATH.'FHL/FengHoLn_ct'.$taskid.'.exe -c '.$task['lport'].' '.$task['ip'].' '.$task['port'].' -t 1 '.'-p '.$task['p'].' -SD '
                .C('FHLdirroot').$task['SD'].' -m '.$task['m'].' -deep 1  -ow 0  -df 1 ';
            $bat = fopen(PATH."FHL/runFengHoln_ct".$taskid.".bat","w");
            fwrite($bat,$cmd.PHP_EOL);
            fclose($bat);
			pclose(popen(PATH."FHL/runFengHoln_ct".$taskid.".bat",'r'));
            //exec($cmd,$out);
            S('fhl_ctask')->update(['run'=>1],["taskid"=>$taskid]);
            if($taskid == 0)
			    $this->json(array('error'=>true,'info'=>'已启动高速远传进程:ct'.$taskid));
            else
                $this->json(array('error'=>true,'info'=>'已启动数据分发进程:ct'.$taskid));
		}elseif($type == 'r'){
			$task = S('fhl_ctask')->query('select * from hy_fhl_stask where taskid = '.$taskid)->fetchALL()[0];
            $this->existFHLexe("FengHoLn_st".$taskid.'.exe');
            $this->existFHLdir(C('FHLdirroot').$task['TD']);
            exec('taskkill /f /im FengHoln_st'.$taskid.'.exe',$out);
			$cmd ='start /b '.PATH.'FHL/FengHoLn_st'.$taskid.'.exe -s '.$task['port'].' -TD '.C('FHLdirroot').$task['TD'].' -m '.$task['m'];
            $bat = fopen(PATH."FHL/runFengHoln_st".$taskid.".bat","w");
            fwrite($bat,$cmd.PHP_EOL);
            fclose($bat);
            pclose(popen(PATH."FHL/runFengHoln_st".$taskid.".bat",'r'));
            S('fhl_stask')->update(['run'=>1],["taskid"=>$taskid]);
			if($taskid == 0)
			    $this->json(array('error'=>true,'info'=>'已启高速远传接收进程:st'.$taskid));
			else
			    $this->json(array('error'=>true,'info'=>'已启数据汇聚进程:st'.$taskid));

		}
	}

	public function killTask(){
		$type = X('get.type');
		$taskid = intval(X('get.taskid'));
		if($type == 't'){
			exec('taskkill /f /im FengHoln_ct'.$taskid.'.exe');
            S('fhl_ctask')->update(['run'=>0],["taskid"=>$taskid]);
            S('fhl_ctask')->query("INSERT INTO eventlog (content, cdt) VALUES ('killtask-t".$taskid."', '".date("Y-m-d H:i:s")."')");
            $this->json(array('error'=>true,'info'=>'已关闭发送进程_ct'.$taskid));
		}elseif($type == 'r'){
			exec('taskkill /f /im FengHoln_st'.$taskid.'.exe');
            S('fhl_stask')->update(['run'=>0],["taskid"=>$taskid]);
            S('fhl_ctask')->query("INSERT INTO eventlog (content, cdt) VALUES ('deletetask-r".$taskid."', '".date("Y-m-d H:i:s")."')");
			$this->json(array('error'=>true,'info'=>'已关闭接收进程_st'.$taskid));
		}
	}
	//清理任务 包括进程和收发文件夹
	public function deleteTask(){
        $type = X('get.type');
        $taskid = intval(X('get.taskid'));
        $delexe = false;
        $deldir = false;
        if($type == 't'){
            $task = S('fhl_ctask')->query('select * from hy_fhl_ctask where taskid = '.$taskid)->fetchALL()[0];
            exec('taskkill /f /im FengHoln_ct'.$taskid.'.exe');
            S('fhl_ctask')->update(['run'=>0],["taskid"=>$taskid]);
            $delexe = $this->delfile(PATH.'FHL/FengHoLn_ct'.$taskid.'.exe');
            $deldir = $this->deldir(C('FHLdirroot').$task['SD']);
            S('fhl_ctask')->query("INSERT INTO eventlog (content, cdt) VALUES ('deletetask-t".$taskid."', '".date("Y-m-d H:i:s")."')");

        }elseif($type == 'r'){
            exec('taskkill /f /im FengHoln_st'.$taskid.'.exe');
            $task = S('fhl_stask')->query('select * from hy_fhl_stask where taskid = '.$taskid)->fetchALL()[0];
            S('fhl_stask')->update(['run'=>0],["taskid"=>$taskid]);
            $delexe = $this->delfile(PATH.'FHL/FengHoLn_st'.$taskid.'.exe');
            $deldir = $this->deldir(C('FHLdirroot').$task['TD']);
            S('fhl_ctask')->query("INSERT INTO eventlog (content, cdt) VALUES ('deletetask-r".$taskid."', '".date("Y-m-d H:i:s")."')");
        }
        if($delexe&&$deldir){
            $this->json(array('error'=>true,'info'=>'已清空任务'.$taskid));
        }else{
            $this->json(array('error'=>false,'info'=>'没有需要清空的内容'.$taskid));
        }
    }
	public function getTaskList(){
	    $currHost = X('get.currHost');
	    $type = X('get.type');
	    if($currHost == 'local'){
	        if($type == 't'){
                $list = S('fhl_ctask')->query('
                      SELECT taskid,lport,ip,port,t,m,p,ow,SD dir,deep,df,info,run,\'t\' type
                      FROM hy_fhl_ctask where taskid = 0
                      UNION
                      SELECT taskid,port lport,\'本节点IP\' ip,port,\'0\' t,m,\'1\' p,\'-\' ow,TD dir,\'-\' deep,\'-\' df,info,run,\'r\' type
                      FROM hy_fhl_stask where taskid > 0
                                        ')->fetchALL();

                $this->json([
                    'error'=>true,
                    'data'=>$list,
                    'count'=>count($list)
                ]);
            }else{
                $list = S('fhl_ctask')->query('
                      SELECT taskid,port lport,\'本节点IP\' ip,port,\'0\' t,m,\'1\' p,\'-\' ow,TD dir,\'-\' deep,\'-\' df,info,run,\'r\' type
                      FROM hy_fhl_stask where taskid = 0
                      UNION
                      SELECT taskid,lport,ip,port,t,m,p,ow,SD dir,deep,df,info,run,\'t\' type
                      FROM hy_fhl_ctask where taskid > 0
                                        ')->fetchALL();

                $this->json([
                    'error'=>true,
                    'data'=>$list,
                    'count'=>count($list)
                ]);

            }

        }
    }
    public function getTaskLog(){
        $type = X('get.type');
        $taskid = intval(X('get.taskid'));
        $start = "";
        $end = "";
        $data = [];
        if($type == "t"){
            $data = S('fhl_ctask')->query("select l.* from (SELECT * FROM clientlog  ORDER BY lid desc limit 1000) l
                                         join hy_fhl_ctask t on t.taskid = ".$taskid." and l.rootDir LIKE '%'||t.SD order by l.lid ")->fetchALL();
        }else{
            $data = S('fhl_ctask')->query("select l.* from (SELECT * FROM serverlog ORDER BY lid desc limit 1000) l
                                         join hy_fhl_stask t on t.taskid = ".$taskid." and l.rootDir LIKE '%'||t.TD order by l.lid")->fetchALL();
        }
        $this->json([
            "error"=>true,
            "data"=>$data,
            "count"=>count($data)
        ]);

    }
    //将FHL路径下的执行文件复制成指定名字
    protected function existFHLexe($exename){
        if(!file_exists(PATH.'FHL/'.$exename)){
           // '文件不存在！';
            copy(PATH.'FHL/FengHoLn.exe', PATH.'FHL/'.$exename);
        }
    }
    //
    protected function existFHLdir($dir){

        if(!file_exists($dir)){
            // '文件不存在！就创建';
            $this->existFHLdir(dirname($dir));
            mkdir($dir);

        }
    }
    protected function delfile($file){
        if(file_exists($file)){
            return unlink($file);
        }else{
            return true;
        }
    }
    //删除非空目录
    protected function deldir($dir) {
        if(!is_dir($dir))
            return false;
        $dh=opendir($dir);
        while ($file=readdir($dh)) {
            if($file!="." && $file!="..") {
                $fullpath=$dir."/".$file;
                if(!is_dir($fullpath)) {
                    unlink($fullpath);
                } else {
                    $this->deldir($fullpath);
                }
            }
        }
        closedir($dh);
        if(rmdir($dir)) {
            return true;
        } else {
            return false;
        }
    }

}
